home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 8206 / 8206.xpi / content / utils.js < prev   
Text File  |  2010-02-02  |  13KB  |  451 lines

  1. var WiseStampUtils = function() {
  2.     var pub = {};
  3.  
  4.     var DEBUG_MODE = null;
  5.       var m_consoleService = null;
  6.       
  7.       var m_nativeJson = null;
  8.       var m_userCode = null;
  9.       
  10.       pub.getDebugMode = function()
  11.       {
  12.           if (DEBUG_MODE == null)
  13.               DEBUG_MODE = WiseStampPrefs.getBoolPref("debug",false);
  14.           
  15.           return DEBUG_MODE;
  16.       }
  17.       
  18.     pub.getRandomInt = function(min, max)
  19.     {
  20.         return Math.floor(Math.random() * (max - min + 1)) + min;
  21.     }
  22.     
  23.     function generateCode(length) 
  24.     {
  25.         /* list all possible characters, similar looking characters and vowels have been removed */
  26.         var possible = '23456789bcdfghjkmnpqrstvwxyz'; 
  27.         var code = '';
  28.         
  29.         for (var i = 0; i < length; i++) 
  30.             code += possible[pub.getRandomInt(0, possible.length-1)];
  31.         
  32.         return code;
  33.     }
  34.     
  35.     // public functions
  36.     pub.getUserCode = function() 
  37.     {
  38.         if (m_userCode == null)
  39.         {
  40.             // create a random code if not created
  41.             m_userCode = WiseStampPrefs.getCharPref("userCode");
  42.             if (m_userCode == "") // failed to read from config
  43.             {
  44.                 m_userCode = generateCode(16); // 16 chars log random number
  45.                 WiseStampPrefs.PREFS.setCharPref("userCode", m_userCode);
  46.             }
  47.         }
  48.         
  49.         return m_userCode;
  50.     }
  51.     
  52.     pub.setUserCode = function(code)
  53.     {
  54.         m_userCode = code;
  55.     }
  56.     
  57.     pub.getVersion = function() 
  58.     {
  59.         var extensionManager = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);  
  60.         var addon = extensionManager.getItemForID("wisestamp@wisestamp.com");  
  61.         return addon.version; 
  62.     }
  63.  
  64.     pub.getAppType = function()
  65.     {
  66.         const FIREFOX_ID = "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}";
  67.         const THUNDERBIRD_ID = "{3550f703-e582-4d05-9a08-453d09bdfdc6}";
  68.         
  69.         var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
  70.         if (appInfo.ID == THUNDERBIRD_ID)
  71.             return "Thunderbird";
  72.         else
  73.             return "Firefox";
  74.     }
  75.     
  76.     pub.getAppVersion = function()
  77.     {
  78.         var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
  79.         return appInfo.version;
  80.     }
  81.     
  82.     pub.getSignaturesFromPref = function()
  83.     {
  84.         //return pub.PREFS.getCharPref("signatures").split(",");
  85.         var ret = null;
  86.         try {
  87.             ret = WiseStampPrefs.PREFS.getComplexValue("signatures",Components.interfaces.nsISupportsString).data.split(",");
  88.         } catch(e)
  89.         {
  90.             alert(e);
  91.         }
  92.         
  93.         return ret;
  94.     }
  95.     
  96.     pub.setSignaturesToPref = function(signatures)
  97.     {
  98.         var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
  99.         str.data = signatures.join(",");
  100.         WiseStampPrefs.PREFS.setComplexValue("signatures",    Components.interfaces.nsISupportsString, str);        
  101.     }
  102.     
  103.     pub.log = function(msg) 
  104.     {
  105.         if (pub.getDebugMode() != true)
  106.             return;
  107.         
  108.         if (this.m_consoleService == null)
  109.             this.m_consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
  110.         
  111.         msg = "WISESTAMP: " + msg;
  112.         this.m_consoleService.logStringMessage(msg)
  113.     }
  114.  
  115.     pub.prompt = function(title,default_val,text)
  116.     {
  117.         var Cc = Components.classes;
  118.         var Ci = Components.interfaces;
  119.           var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
  120.         var check = {value: null};
  121.         var input = {value: default_val};
  122.         var result = prompts.prompt(window, 
  123.                         WisestampSignatureFactory.strings.GetStringFromName(title),
  124.                         WisestampSignatureFactory.strings.GetStringFromName(text), input, null, check);
  125.         
  126.         if (result == false)
  127.             return null;
  128.             
  129.         if (input.value == default_val)
  130.             return "";
  131.             
  132.         return input.value;
  133.     }
  134.   
  135.       pub.confirm = function(title,text,button1,button2,button3)
  136.     {
  137.         var Cc = Components.classes;
  138.         var Ci = Components.interfaces;
  139.           var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
  140.         var check = {value: null};
  141.         
  142.         var flags = 
  143.             prompts.BUTTON_POS_0 * prompts.BUTTON_TITLE_IS_STRING + 
  144.             prompts.BUTTON_POS_1 * prompts.BUTTON_TITLE_IS_STRING;
  145.         
  146.         if (button3 != undefined)
  147.             flags += prompts.BUTTON_POS_2 * prompts.BUTTON_TITLE_IS_STRING;
  148.           
  149.           var selected = prompts.confirmEx(
  150.               window,
  151.               WisestampSignatureFactory.strings.GetStringFromName(title),
  152.               WisestampSignatureFactory.strings.GetStringFromName(text),
  153.             flags, 
  154.             button1 == undefined ? "" : WisestampSignatureFactory.strings.GetStringFromName(button1), 
  155.             button2 == undefined ? "" : WisestampSignatureFactory.strings.GetStringFromName(button2), 
  156.             button3 == undefined ? "" : WisestampSignatureFactory.strings.GetStringFromName(button3), 
  157.             null, check);
  158.           
  159.         return selected;
  160.     }
  161.   
  162.       pub.alert = function(text,title)
  163.     {
  164.         if (title == null)
  165.             title = "application_name";
  166.         
  167.         pub.alert2(WisestampSignatureFactory.strings.GetStringFromName(text),WisestampSignatureFactory.strings.GetStringFromName(title));
  168.     }
  169.  
  170.     pub.alert2 = function(text,title)
  171.     {
  172.         if (title == null)
  173.             title = WisestampSignatureFactory.strings.GetStringFromName("application_name");
  174.             
  175.         var Cc = Components.classes;
  176.         var Ci = Components.interfaces;
  177.           var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
  178.         prompts.alert(window, title, text);
  179.     }
  180.  
  181.     pub.openSite = function (aURL) 
  182.     {
  183.         WisestampGetAppObject().openSite(aURL);
  184.     }
  185.  
  186.     pub.md5 = function(string)
  187.     {
  188.         var converter =
  189.             Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
  190.             createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  191.  
  192.         // we use UTF-8 here, you can choose other encodings.
  193.         converter.charset = "UTF-8";
  194.  
  195.         // result is an out parameter, result.value will contain the array length
  196.         var result = {};
  197.         
  198.         // data is an array of bytes
  199.         var data = converter.convertToByteArray(string, result);
  200.  
  201.         var ch = Components.classes["@mozilla.org/security/hash;1"].createInstance(Components.interfaces.nsICryptoHash);
  202.         ch.init(ch.MD5);
  203.         ch.update(data, data.length);
  204.  
  205.         var hash = ch.finish(false);
  206.         
  207.         // return the two-digit hexadecimal code for a byte
  208.         function toHexString(charCode)
  209.         {
  210.             return ("0" + charCode.toString(16)).slice(-2);
  211.         }
  212.         
  213.         // convert the binary hash data to a hex string.
  214.         var md5string = [toHexString(hash.charCodeAt(i)) for (i in hash)].join("");
  215.         return md5string;
  216.     }
  217.     
  218.     pub.exportLog = function(file)
  219.     {
  220.         // file is nsIFile, data is a string
  221.         var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
  222.         
  223.         // use 0x02 | 0x10 to open file for appending.
  224.         foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0); 
  225.  
  226.         // if you are sure there will never ever be any non-ascii text in data you can 
  227.         // also call foStream.writeData directly
  228.         var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].createInstance(Components.interfaces.nsIConverterOutputStream);
  229.         converter.init(foStream, "UTF-8", 0, 0);
  230.  
  231.         var messages = {};
  232.         var count = {};
  233.         this.m_consoleService.getMessageArray(messages,count);
  234.         for (var i = 0; i < count.value; i++)
  235.         {
  236.             try
  237.             {
  238.                 var message = messages.value[i];
  239.                 var text = message.message;
  240.                 
  241.                 if (message.sourceName)
  242.                     text += "\n\rSource: " + message.sourceName + ", line: " + message.lineNumber;
  243.                 
  244.                 if (text.toLowerCase().indexOf('wisestamp') == -1)
  245.                     continue;
  246.                 
  247.                 converter.writeString(text + '\r\n');
  248.                 
  249.             } catch(e)
  250.             {
  251.                 WiseStampUtils.log("utils.js :: exportLog :: exception caught = " + e);
  252.             }
  253.         }
  254.         
  255.         converter.close(); // this closes foStream
  256.     }
  257.  
  258.     pub.browseFile = function(openFile,type,typeExt)
  259.     {
  260.         var nsIFilePicker = Components.interfaces.nsIFilePicker;
  261.         var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  262.         
  263.         var mode = (openFile == true) ? nsIFilePicker.modeOpen : nsIFilePicker.modeSave;
  264.         fp.init(window, "Select a File", mode);
  265.         if (type != undefined)
  266.         {
  267.             fp.appendFilter(type + " (*."+typeExt+")", "*."+typeExt);
  268.             fp.defaultExtension = typeExt;
  269.         }
  270.         
  271.         var res = fp.show();
  272.         if (res == nsIFilePicker.returnOK)
  273.             return fp.file;
  274.  
  275.         return null;        
  276.     }
  277.  
  278.     pub.strip_tags = function(str, allowed_tags) 
  279.     {
  280.         var key = '', allowed = false;
  281.         var matches = [];
  282.         var allowed_array = [];
  283.         var allowed_tag = '';
  284.         var i = 0;
  285.         var k = '';
  286.         var html = '';
  287.     
  288.         var replacer = function (search, replace, str) {
  289.             return str.split(search).join(replace);
  290.         };
  291.     
  292.         // Build allowes tags associative array
  293.         if (allowed_tags) {
  294.             allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
  295.         }
  296.     
  297.         str += '';
  298.     
  299.         // Match tags
  300.         matches = str.match(/(<\/?[\S][^>]*>)/gi);
  301.     
  302.         // Go through all HTML tags
  303.         for (key in matches) {
  304.             if (isNaN(key)) {
  305.                 // IE7 Hack
  306.                 continue;
  307.             }
  308.     
  309.             // Save HTML tag
  310.             html = matches[key].toString();
  311.     
  312.             // Is tag not in allowed list? Remove from str!
  313.             allowed = false;
  314.     
  315.             // Go through all allowed tags
  316.             for (k in allowed_array) {
  317.                 // Init
  318.                 allowed_tag = allowed_array[k];
  319.                 i = -1;
  320.     
  321.                 if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
  322.                 if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
  323.                 if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
  324.     
  325.                 // Determine
  326.                 if (i == 0) {
  327.                     allowed = true;
  328.                     break;
  329.                 }
  330.             }
  331.     
  332.             if (!allowed) {
  333.                 str = replacer(html, "", str); // Custom replace. No regexing
  334.             }
  335.         }
  336.     
  337.         return str;
  338.     };
  339.     
  340.     ///////////////////////////////////////////////////////
  341.     
  342.     function getJSON()
  343.     {
  344.         if (this.m_nativeJson == null)
  345.         {            
  346.             try {
  347.                 var Ci = Components.interfaces;
  348.                 var Cc = Components.classes;
  349.                 this.m_nativeJson = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
  350.             
  351.             } catch (e) { // TB2 doesn't support this interface
  352.                 this.m_nativeJson = {decode:function(){return '';},encode:function(){return '';}};
  353.             }        
  354.         }
  355.         
  356.         return this.m_nativeJson;
  357.     }
  358.     
  359.     pub.parseSerialized = function(serialized)
  360.     {
  361.         return getJSON().decode(serialized);  
  362.     }
  363.     
  364.     pub.serialize = function(object)
  365.     {
  366.         return getJSON().encode(object);
  367.     }
  368.     
  369.     ///////////////////////////////////////////////////////
  370.     
  371.     function getLoginInfo(username)
  372.     {
  373.         var hostname = 'chrome://wisestamp';
  374.         var loginManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
  375.         var logins = loginManager.findLogins({}, hostname, "", "Login");
  376.           
  377.         // Find user from returned array of nsILoginInfo objects
  378.         for (var i = 0; i < logins.length; i++) 
  379.         {
  380.             WiseStampUtils.log("[utils.js::getLoginInfo] username/password = " + logins[i].username + '/' + logins[i].password);
  381.             
  382.             if (logins[i].username == username) 
  383.                 return logins[i];
  384.         }
  385.         
  386.         return null;
  387.     }
  388.     
  389.     pub.storePassword = function(username,password)
  390.     {
  391.         var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",Components.interfaces.nsILoginInfo,"init");
  392.         var loginInfo = new nsLoginInfo('chrome://wisestamp',"","Login",username,password,"","");
  393.         
  394.         var loginManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
  395.         
  396.         var oldLoginInfo = getLoginInfo(username);
  397.         WiseStampUtils.log("[utils.js::storePassword] username/password = " + username + '/' + oldLoginInfo.password);
  398.         if (oldLoginInfo == null)
  399.             loginManager.addLogin(loginInfo);
  400.         else
  401.             loginManager.modifyLogin(oldLoginInfo, loginInfo);
  402.     }
  403.     
  404.     pub.getPassword = function(username)
  405.     {
  406.         var loginInfo = getLoginInfo(username);
  407.         if (loginInfo != null)
  408.             return loginInfo.password;
  409.         
  410.         return null;
  411.     }
  412.                 
  413.     return pub;
  414. }();
  415.  
  416.  
  417. /*
  418. // Call stack code
  419.     showCallStack: function(){
  420.         var f=this.showCallStack,result="Call stack:\n\n";
  421.         alert(f.name);
  422.         alert(f.arguments.callee);
  423.         while((f=f.caller)!==null)
  424.         {
  425.             var match = f.toString().match(/^function \((.*)\)/);
  426.             if (match == null)
  427.             {
  428.                 alert(f.toString());
  429.                 break;
  430.             }
  431.             
  432.             result += "F:" + match[0] + "\n";
  433.             result += "A:" + this.parseArguments(f.arguments) + "\n";
  434.             result += "\n";
  435.         }
  436.         alert(result);
  437.     },
  438.     
  439.     parseArguments: function(a){
  440.         var result=[];
  441.     
  442.         for(var i=0; i<a.length; i++){
  443.             if ('string' == typeof a[i])
  444.                 result.push("\"" + a[i] + "\"");
  445.             else
  446.                 result.push(a[i]);
  447.         }
  448.     
  449.         return "(" + result.join(", ") + ")";
  450.     },
  451. */